package cn.yunhe.servlet;

import cn.yunhe.entity.News;
import cn.yunhe.service.NewsService;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/NewsListServlet")
public class NewsListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获得当前页
        String currPage = request.getParameter("pageIndex");
        //如果当前页为空，说明是第一页，就让他等于1
        if (currPage == null) {
            currPage = "1";
        }
        int pageIndex = Integer.parseInt(currPage);
        //得到总条数
        NewsService newsService = new NewsService();
        int totalDatas = newsService.getNewsCount();
        //算出总页数
        int totalPages = PageUtil.getTotalPages(totalDatas);
        //如果当前页小于第一页，或大于总页数,处理一下
        if (pageIndex < 1) {
            pageIndex = 1;
        }
        if (pageIndex > totalPages) {
            pageIndex = totalPages;
        }
        //得到关键字
        String keyword = request.getParameter("keyword");
        request.setAttribute("keyword",keyword);

        //调用service层的方法，得到list，传递给页面
        List<News> newsList = newsService.getNewsByPage(pageIndex, keyword);

        //存储list和当前页，以便页面中取出使用
        request.setAttribute("pageIndex", pageIndex);
        request.setAttribute("newsList", newsList);
        request.setAttribute("totalPages", totalPages);

        request.getRequestDispatcher("main.jsp").forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
